package org.jeecg.modules.demo.util;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jeecg.modules.demo.weixin.dto.ProfitSharingDto;
import org.jeecg.modules.demo.weixin.entity.MerchantPay;
import org.jeecg.modules.demo.weixin.entity.PayOrder;
import org.jeecg.modules.demo.weixin.util.PayConstants;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

@Data
public class ProfitUtil {

    private static CloseableHttpClient httpClient;

    private static String mchSetup() {
        // 加载商户私钥（privateKey：私钥字符串）
        PrivateKey merchantPrivateKey = PemUtil
                .loadPrivateKey(new ByteArrayInputStream(PayConstants.PRIVATE_KEY.getBytes(StandardCharsets.UTF_8)));

        // 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3密钥）
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(PayConstants.MCH_ID_SERVICE, new PrivateKeySigner(PayConstants.MCH_SERIAL_NO, merchantPrivateKey)), PayConstants.API_V2KEY_SERVICE.getBytes(StandardCharsets.UTF_8));
        String string = verifier.getValidCertificate().getSerialNumber().toString(16);
        // 初始化httpClient
        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(PayConstants.MCH_ID_SERVICE, PayConstants.MCH_SERIAL_NO, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
        return string;
    }


    /**
     * 分账
     *
     * @param profitSharingDto
     * @return
     */
    @SneakyThrows
    public static JSONObject sharing(ProfitSharingDto profitSharingDto, PayOrder payOrder, String subMch) {
        String plate = mchSetup();
//        //微信支付的单位是分，要转换一下
        BigDecimal decimal = payOrder.getPayPrice().multiply(BigDecimal.valueOf(100)).multiply(BigDecimal.valueOf(0.3)).setScale(2, 4);
//        //生成随机数
//        String nonceStr = WXPayUtil.generateNonceStr();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sub_mchid",subMch);
        jsonObject.put("appid", PayConstants.App_ID_SERVICE);
        jsonObject.put("transaction_id", payOrder.getTransactionId());
        jsonObject.put("out_order_no", String.valueOf(payOrder.getId()));
//        jsonObject.put("unfreeze_unsplit", profitSharingDto.getUnfreezeUnsplit());

        //添加接收方
        JSONArray jsonArray = new JSONArray();
//        JSONObject receiver = new JSONObject();
//        receiver.put("type", "MERCHANT_ID");
//        receiver.put("account", merchantPay.getMchId());
//        receiver.put("amount", Integer.parseInt(amount));
//        receiver.put("description", "分账");
//        jsonArray.add(receiver);
        if (CollectionUtils.isEmpty(profitSharingDto.getReceiverList())) {
            return null;
        }
        profitSharingDto.getReceiverList().forEach(smtProfitsharingReceiver -> {
            JSONObject receiver = new JSONObject();
            receiver.put("type", smtProfitsharingReceiver.getType());
            receiver.put("account", smtProfitsharingReceiver.getComId());
            //最大及时订单的百分之三十
//            int value = decimal.multiply(smtProfitsharingReceiver.get()).setScale(2, 4).intValue();
            receiver.put("amount", smtProfitsharingReceiver.getSplitAccount());
            receiver.put("description", smtProfitsharingReceiver.getDescription());
            jsonArray.add(receiver);
        });
        jsonObject.put("receivers", jsonArray);
        String url = "https://api.mch.weixin.qq.com/v3/profitsharing/orders";

        HttpPost post = new HttpPost(url);
        post.addHeader("Accept", "application/json");
        post.setHeader("Content-Type", "application/json; charset=utf-8");
        StringEntity postingString = new StringEntity(JSONObject.toJSONString(jsonObject), "utf-8");
        post.setEntity(postingString);
        CloseableHttpResponse response = null;
        response = httpClient.execute(post);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != 200) {
            return null;
        }
        String content = EntityUtils.toString(response.getEntity());
        JSONObject result = JSONObject.parseObject(content);

        return result;
    }

    /**
     * 添加分账接收方
     *
     * @param
     * @param type
     * @param name
     * @param account
     * @param relationType
     * @return
     */
    @SneakyThrows
    public static JSONObject addShar( String subMer ,String type, String name, String account, String relationType) {
        String plate = mchSetup();
        //给名字加密 敏感需要加密
        String rsaEncryptOAEP = VechatPayV3Util.encryption(name, plate);

        System.out.println(rsaEncryptOAEP);
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("sub_mchid", subMer);
        jsonParam.put("appid", PayConstants.App_ID_SERVICE);
        jsonParam.put("type", type);
        jsonParam.put("name", rsaEncryptOAEP);
        jsonParam.put("account", account);
        jsonParam.put("relation_type", relationType);
        String url = "https://api.mch.weixin.qq.com/v3/profitsharing/receivers/add";

        HttpPost post = new HttpPost(url);
        post.addHeader("Accept", "application/json");
        //获取平台的证书
        post.addHeader("Wechatpay-Serial", plate);
        post.setHeader("Content-Type", "application/json; charset=utf-8");
        StringEntity postingString = new StringEntity(JSONObject.toJSONString(jsonParam), "utf-8");
        post.setEntity(postingString);
        CloseableHttpResponse response = null;
        response = httpClient.execute(post);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != 200) {
            return null;
        }
        String content = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = JSONObject.parseObject(content);
        return jsonObject;
    }


    /**
     * 查询分账状态
     * @param outOrderNo
     * @param specialSubMerchants
     * @param transactionId
     * @return
     */
    @SneakyThrows
    public static JSONObject querySharing(String outOrderNo, String specialSubMerchants, String transactionId) {
        mchSetup();
        //查询分账信息
        String url = "https://api.mch.weixin.qq.com/v3/profitsharing/orders/{0}?sub_mchid={1}&transaction_id={2}";
        //调用查询接口进行替换数据
        String get = url.replace("{0}", String.valueOf(outOrderNo)).replace("{1}", specialSubMerchants).replace("{2}", transactionId);

        HttpGet httpGet = new HttpGet(get);
        httpGet.addHeader("Accept", "application/json");
        httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
        CloseableHttpResponse response = null;
        response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != 200) {
            return null;
        }
        String content = EntityUtils.toString(response.getEntity());
        JSONObject result = JSONObject.parseObject(content);
        return result;
    }


//    /**
//     * 退回分账金额   需要商户在微信支付开启分账退还   一般情况下 分账的金额都是已经不退换的订单
//     *
//     * @param profitSharingDto
//     * @return
//     */
//    @SneakyThrows
//    @PostMapping("/refundSharing")
//    public Result<?> refundSharing(@RequestBody ProfitSharingDto profitSharingDto, HttpServletRequest request) {
//        this.mchSetup();
//        //根据商家id查询商家配置的支付信息
//        QueryWrapper<MerchantPay> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("merchant_id", Integer.valueOf(profitSharingDto.getMerId()));
//        MerchantPay merchantPay = merchantPayService.getOne(queryWrapper);
//        //判断订单
//        PayOrder payOrder = payOrderService.getById(profitSharingDto.getOutTradeNo());
//        if (!payOrder.getPayStatus().equals("2")) {
//            return Result.error(606, "当前订单未支付完成或者已经退款！");
//        }
////        //微信支付的单位是分，要转换一下
//        String amount = String.valueOf(payOrder.getPayPrice().multiply(BigDecimal.valueOf(100)).multiply(BigDecimal.valueOf(0.3)).intValue());
//
//        JSONObject jsonParam = new JSONObject();
//        jsonParam.put("sub_mchid", merchantPay.getSpecialSubMerchants());
//        jsonParam.put("out_order_no", "36000100912023111781150127189");
////        jsonParam.put("order_id", "36000100912023111781150127189");
//        jsonParam.put("out_return_no", String.valueOf(payOrder.getId()));
//        jsonParam.put("return_mchid", PayConstants.MCH_ID_SERVICE);
//        jsonParam.put("amount", Integer.parseInt(amount));
//        jsonParam.put("description", "回退");
//        String url = "https://api.mch.weixin.qq.com/v3/profitsharing/return-orders";
//        HttpPost post = new HttpPost(url);
////        post.addHeader("Authorization", "WECHATPAY2-SHA256-RSA2048" + " " + strToken);
//        post.addHeader("Accept", "application/json");
////        post.addHeader("Wechatpay-Serial", PayConstants.MCH_SERIAL_NO);
//        post.setHeader("Content-Type", "application/json; charset=utf-8");
//        StringEntity postingString = new StringEntity(JSONObject.toJSONString(jsonParam), "utf-8");
//        post.setEntity(postingString);
//        CloseableHttpResponse response = null;
//        response = httpClient.execute(post);
//        String content = EntityUtils.toString(response.getEntity());
//        JSONObject jsonObject = JSONObject.parseObject(content);
//        return Result.ok(jsonObject);
//
//    }


    @SneakyThrows
    public static JSONObject del(String subMchid, String type, String account) {
        String plate = mchSetup();
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("sub_mchid", subMchid);
        jsonParam.put("appid", PayConstants.App_ID_SERVICE);
        jsonParam.put("type", type);
        jsonParam.put("account", account);
//        jsonParam.put("sub_mchid", "1610777891");
//        jsonParam.put("appid", PayConstants.App_ID_SERVICE);
//        jsonParam.put("type", "MERCHANT_ID");
//        jsonParam.put("account", "1302752201");
        String url = "https://api.mch.weixin.qq.com/v3/profitsharing/receivers/delete";

        HttpPost post = new HttpPost(url);
        post.addHeader("Accept", "application/json");
        post.addHeader("Wechatpay-Serial", plate);
        post.setHeader("Content-Type", "application/json; charset=utf-8");
        StringEntity postingString = new StringEntity(JSONObject.toJSONString(jsonParam), "utf-8");
        post.setEntity(postingString);
        CloseableHttpResponse response = null;
        response = httpClient.execute(post);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != 200) {
            return null;
        }
        String content = EntityUtils.toString(response.getEntity());
        JSONObject result = JSONObject.parseObject(content);
        return result;
    }


}
